package piuk.merchant; 
 
import org.apache.commons.io.IOUtils; 
import org.apache.commons.codec.binary.Hex; 
import org.json.simple.JSONArray; 
import org.json.simple.JSONObject; 
import org.json.simple.JSONValue; 
 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.Map; 
 
@SuppressWarnings("unchecked") 
public class MerchantClient { 
    public final String guid; 
    public final String password; 
    public final String secondPassword; 
    public final String HTTP_ROOT = "https://blockchain.info/zh-cn/";
    public final String BTCE_URL = "https://btc-e.com/api/2/btc_usd/ticker";
 
    public MerchantClient(String guid, String password, String secondPassword) { 
        super(); 
        this.guid = guid; 
        this.password = password; 
        this.secondPassword = secondPassword; 
    } 
    
    public static class AddressBean { 
         long balance; 
         long total_received; 
         String address; 
         String label; 
 
        public long getBalance() { 
            return balance; 
        } 
 
        public long getTotal_received() { 
            return total_received; 
        } 
 
        public String getAddress() { 
            return address; 
        } 
 
        public String getLabel() { 
            return label; 
        } 
        public String setAddress(String address) { 
            return this.address = address; 
        } 
 
        public String setLabel(String label) { 
            return this.label = label; 
        } 
    } 
 
    private static String fetchURL(String URL) throws Exception { 
        URL url = new URL(URL); 
 
        HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
 
        connection.addRequestProperty("Accept", "application/xml"); 
 
        connection.setConnectTimeout(10000); 
 
        connection.setInstanceFollowRedirects(false); 
 
        connection.connect(); 
 
        if (connection.getResponseCode() != 200) { 
            throw new Exception("Invalid HTTP Response code " + connection.getResponseCode()); 
        } 
 
        return IOUtils.toString(connection.getInputStream(), "UTF-8"); 
    } 
 
    public AddressBean generateAddresses(String label) throws Exception { 
        AddressBean addressBean = new AddressBean(); 
        String response = fetchURL(HTTP_ROOT +  "merchant/" + guid + "/new_address?password="+password +
        		"&second_password="+secondPassword+"&label="+label); 
 
        if (response == null) 
            throw new Exception("Null Reponse"); 
 
        Map<String, Object> obj = (Map<String, Object>) JSONValue.parse(response); 
        addressBean.setAddress((String)obj.get("address"));
        addressBean.setLabel((String)obj.get("label"));
 
        return addressBean; 
    } 
    
    public List<AddressBean> getAddresses() throws Exception { 
        List<AddressBean> data = new ArrayList<AddressBean>(); 
 
        String response = fetchURL(HTTP_ROOT +  "merchant/" + guid + "/list?password="+password); 
 
        if (response == null) 
            throw new Exception("Null Reponse"); 
 
        Map<String, Object> obj = (Map<String, Object>) JSONValue.parse(response); 
 
        if (obj.get("error") != null) 
            throw new Exception((String) obj.get("error")); 
 
        JSONArray addresses = (JSONArray)obj.get("addresses"); 
 
 
        for (int ii = 0; ii < addresses.size(); ++ii) { 
            JSONObject address_obj = (JSONObject)addresses.get(ii); 
 
            AddressBean bean = new AddressBean(); 
 
            bean.balance = (Long)address_obj.get("balance"); 
            bean.total_received = (Long)address_obj.get("total_received"); 
            bean.address = (String)address_obj.get("address"); 
            bean.label = (String)address_obj.get("label"); 
 
            data.add(bean); 
        } 
 
        return data; 
    } 
 
    public long getBalance() throws Exception { 
        String response = fetchURL(HTTP_ROOT +  "merchant/" + guid + "/balance?password="+password); 
 
        if (response == null) 
            throw new Exception("Null Reponse"); 
         
        Map<String, Object> obj = (Map<String, Object>) JSONValue.parse(response); 
         
        if (obj.get("error") != null) 
            throw new Exception((String) obj.get("error")); 
         
        return (Long)obj.get("balance"); 
    } 
 
    public byte[] makePayment(String address, long amount) throws Exception { 
        String response = fetchURL(HTTP_ROOT +  "merchant/" + guid + "/payment?password="+password+"&second_password="+secondPassword+"&address="+address+"&amount="+amount); 
         
        if (response == null) 
            throw new Exception("Null Reponse"); 
         
        Map<String, Object> obj = (Map<String, Object>) JSONValue.parse(response); 
         
        if (obj.get("error") != null) 
            throw new Exception((String) obj.get("error")); 
         
        if (obj.get("tx_hash") != null) 
            return Hex.decodeHex(((String) obj.get("tx_hash")).toCharArray()); 
        else  
            throw new Exception("No transaction hash provided"); 
    } 
    public static void  main(String []args) throws Exception{ 
    	MerchantClient merchantClient = new MerchantClient("8522ea15-25c9-f837-9e8d-8892253fd3fb","goxbtcwallet","goxbtcwallet");
    	System.out.println(merchantClient.getAddresses());
    	//System.out.println(merchantClient.generateAddresses("zhougui").getAddress());
    	//System.out.println(merchantClient.getBalance());
    }
}